package com.Lubaichen.Wiki.service;

import com.Lubaichen.Wiki.Exception.BusinessException;
import com.Lubaichen.Wiki.Exception.BusinessExceptionCode;
import com.Lubaichen.Wiki.Pojo.User;
import com.Lubaichen.Wiki.Pojo.UserExample;
import com.Lubaichen.Wiki.mapper.UserMapper;
import com.Lubaichen.Wiki.req.UserLoginReq;
import com.Lubaichen.Wiki.req.UserQueryReq;
import com.Lubaichen.Wiki.req.UserResetPasswordReq;
import com.Lubaichen.Wiki.req.UserSaveReq;
import com.Lubaichen.Wiki.resp.UserLoginResp;
import com.Lubaichen.Wiki.resp.UserQueryResp;
import com.Lubaichen.Wiki.resp.PageResp;
import com.Lubaichen.Wiki.utils.CopyUtil;
import com.Lubaichen.Wiki.utils.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.rmi.CORBA.Util;
import java.util.Collections;
import java.util.List;

/**
 * @author Lubaichen
 * @date 2022年02月28日 22:18
 */
@Service
public class UserService {

    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
    // @Resource :JDK自带的注解，可以取代@Autowired
    @Autowired
    private UserMapper userMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<UserQueryResp> list(UserQueryReq req) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();// Criteria ： 相当于where条件
        if (!ObjectUtils.isEmpty(req.getLoginName())) {
            criteria.andNameLike("%" + req.getLoginName() + "%");
        }
        // PageHelper只对第一条sql语句生效，如果后面还有sql，那么后面这句sql就没有分页效果。
        PageHelper.startPage(req.getPage(), req.getSize());
        List<User> users = userMapper.selectByExample(userExample);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        LOG.info("总页数:{}", (pageInfo.getPages()));
        LOG.info("总行数:{}", (pageInfo.getTotal()));
        PageResp<UserQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(CopyUtil.copyList(users, UserQueryResp.class));
        return pageResp;
    }


    public void save(UserSaveReq req) {
        User user = CopyUtil.copy(req, User.class);
        String loginName = req.getLoginName();
        if (!ObjectUtils.isEmpty(req.getId())) { // 如果传来的req有id值，那么只进行更新。
            user.setLoginName(null);
            user.setPassword(null);
            userMapper.updateByPrimaryKeySelective(user);
        } else { // 如果没有就插入
            User userDB = selectByLoginName(loginName);
            if (ObjectUtils.isEmpty(userDB)) {
                user.setId(snowFlake.nextId()); // 雪花算法生成id
                userMapper.insert(user);
            }
            else {
                // 用户名已存在
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        }
    }


    public void deleteUserById(Long id) {
        if (!ObjectUtils.isEmpty(id)) {
            userMapper.deleteByPrimaryKey(id);
        }
    }

    public User selectByLoginName(String LoginName) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andLoginNameEqualTo(LoginName);
        List<User> users = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(users)) return null;
        return users.get(0);
    }


    public void resetPassword(UserResetPasswordReq req) {
//        UserExample userExample = new UserExample();
//        UserExample.Criteria criteria = userExample.createCriteria();
//        criteria.andIdEqualTo(req.getId());
//        List<User> users = userMapper.selectByExample(userExample);
//        User user = users.get(0);
//        user.setPassword(req.getPassword());
//        userMapper.updateByExample(user, userExample);
        User user = CopyUtil.copy(req, User.class);
        userMapper.updateByPrimaryKeySelective(user);
    }

    public UserLoginResp login(UserLoginReq req) {
        User userDb = selectByLoginName(req.getLoginName());
        if (ObjectUtils.isEmpty(userDb)) {
            // 用户名不存在
            LOG.info("用户名不存在,{}", req.getLoginName());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        } else {
            if (userDb.getPassword().equals(req.getPassword())) {
                // 登录成功
                return CopyUtil.copy(userDb, UserLoginResp.class);
            } else {
                // 密码不对
                LOG.info("密码不对, 输入密码:{}, 数据库密码:{}", req.getLoginName(), userDb.getPassword());
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }
}
